<template>
	<div class="upload-component-box">
		<el-dialog
			top="10vh"
			width="805px"
			title="批量导入"
			:close-on-click-modal="false"
			:visible.sync="dialogVisible"
			@closed="closeTheBox"
		>
			<section class="content">
				<el-steps v-if="isAnalysis === 1 && isCheck === 1" :active="active" align-center class="upload-component--step">
					<el-step>
						<div class="slot-file" slot="title">上传文件
							<div class="el-step__line" style="margin-right: 0px;">
								<i class="el-step__line-inner" style="transition-delay: 0ms; border-width: 0px; width: 0%;"></i>
							</div>
						</div>
					</el-step>
					<el-step>
						<div class="slot-file" slot="title">数据校验
							<div class="el-step__line" style="margin-right: 0px;">
								<i class="el-step__line-inner" style="transition-delay: 0ms; border-width: 0px; width: 0%;"></i>
							</div>
						</div>
					</el-step>
					<el-step>
						<div slot="title">导入数据</div>
					</el-step>
				</el-steps>
				<el-steps v-else :active="active" align-center class="upload-component--step">
					<el-step>
						<div class="slot-file" slot="title">上传文件
							<div class="el-step__line" style="margin-right: 0px;">
								<i class="el-step__line-inner" style="transition-delay: 0ms; border-width: 0px; width: 0%;"></i>
							</div>
						</div>
					</el-step>
					<el-step>
						<div slot="title">导入数据</div>
					</el-step>
				</el-steps>
			</section>
			<article class="main" v-if="active === 1">
				<div class="download" v-if="isAnalysis !== 0">
					<div class="download_left">
						<img src="@assets/img/pc-trm-xzmb-icon@1x.png" alt="">
					</div>
					<div class="download_right_one">
						<p class="title_box">填写导入数据信息</p>
						<p class="center_box"> {{configureList.describeOne}} </p>
						<span>
							<el-button class="downloadTemplate" type="text" @click.stop="templateDownload">下载模板</el-button>
						</span>
					</div>
				</div>
				<div class="download">
					<div class="download_left">
						<img src="@assets/img/pc-trm-scwj-icon@1x.png" alt="">
					</div>
					<div class="download_right">
						<p class="title_box">上传填好的信息表</p>
						<p class="center_box">{{ configureList.describeTwo }}</p>
						<el-upload
							action=""
							class="upload-demo"
							with-credentials
							:accept="dataUpload.uploadAccept"
							:auto-upload="false"
							:multiple='isSingle === 1 ? false : true'
							:limit="isSingle === 1 ? 1 : 0"
							:file-list="dataUpload.fileDataList"
							:before-remove="beforeRemove"
							:on-change="uploadChange"
							:before-upload="onBeforeUpload"
						>
							<el-button :disabled="isSingle === 1 && dataUpload.fileDataList.length !== 0" class="downloadTemplate" style="padding:0 0;" type="text">点击上传</el-button>
						</el-upload>
					</div>
				</div>
			</article>
			<article v-if="isAnalysis === 1 && isCheck === 1 && active === 2" class="main_second">
				<div class="download_second">
					<span class="number">正常数量条数: &nbsp;&nbsp;<span style="color:#00DD00;font-weight: bold;">{{ successesNumber }}条</span></span>
					<span class="number">异常数量条数: &nbsp;&nbsp;<span style="color:red;font-weight: bold;">{{ failNumber }}条</span></span>
				</div>
				<div class="abnormal_prompt">
					<div class="abnormal_prompt_title">异常提示</div>
					<div v-if="errorStatus === 'CHECKFAIL'" class="download_exception" >
						<div class="download_exception_left">
							<m-iconfont classify='taiermao' icon='iconpc-other_cwtswj1x' size="14" color="#666666"/>
							<el-tooltip
								class="item" 
								effect="dark" 
								:content="this.exceptionName" 
								placement="top"
							>
								<span class="error_message">{{this.exceptionName}}错误提示文件.txt</span>
							</el-tooltip>
						</div>
						<div class="download_exception_right" @click="getDownloadException">
							<el-tooltip class="item" effect="dark" content="下载" placement="top-start">
								<m-iconfont classify='taiermao' icon='iconxiazai1x' size="14" />
							</el-tooltip>
						</div>
					</div>
					<div class="abnormal_prompt_content">
						<p>{{ exceptionList }}</p>
					</div>
				</div>
			</article>
			<article class="main_third" v-if="isAnalysis === 1 && isCheck === 1 ? active === 3 : active === 2">
				<div class="progress">
					<div class="progress_content">
						<el-progress class="progressBar" :show-text="false" :stroke-width="16" :percentage="progressVal" />&nbsp;&nbsp;&nbsp;
						<p class="percentage">{{ progressVal }}%</p>
					</div>
					<span class="tip">正在导入...</span>
        </div>
			</article>
			<span v-if="active !== 3" slot="footer" class="dialog-footer">
				<el-button v-if="active === 1" @click="closeTheBox">取 消</el-button>
				<!-- 解析类的校验第一步《下一步》按钮 -->
				<el-button 
					v-if="isAnalysis === 1 && isCheck === 1 ? active === 1 : ''" 
					:disabled="dataUpload.fileDataList.length === 0" 
					type="primary" 
					@click="nextStepOpen" 
					:loading="loading">下一步</el-button>
				<!-- 解析类的不校验第一步《下一步》按钮 -->
				<el-button 
					v-if="isAnalysis === 1 && isCheck === 0 ? active === 1 : ''" 
					:disabled="dataUpload.fileDataList.length === 0" 
					type="primary" 
					@click="onCheckNextStepOpen" 
					:loading="loading">下一步</el-button>
				<!-- 非解析类的不校验第一步《下一步》按钮 -->
				<el-button 
					v-if="isAnalysis === 0 ? active === 1 : ''" 
					:disabled="dataUpload.fileDataList.length === 0" 
					type="primary" 
					@click="nonAnalyticNextStepOpen" 
					:loading="loading">下一步</el-button>
				<!-- 解析类的校验第二部按钮 -->
				<el-button v-if="isAnalysis === 1 && isCheck === 1 ? active === 2 : active === 3" 
					@click="lastStep">重新上传</el-button>
				<el-button 
					v-if="isAnalysis === 1 && isCheck === 1 ? active === 2 : active === 3"  
					type="primary" 
					:disabled="imgFallError.status !== 'CHECKSUCCESSFUL'"
					@click="secondNextStepOpen">下一步</el-button>
			</span>
		</el-dialog>
		<el-dialog
			top="10vh"
			width="805px"
			title="批量导入"
			:close-on-click-modal="false"
			:visible.sync="importComplete"
			@closed="closePage"
		>
			<div v-if="imgFallError.status === 'SAVESUCCESSFUL' || imgFallError.status === 'CHECKSUCCESSFUL' || nonAnalyticimgExhibition" class="import_content">
				<img class="import_content_img" src="@assets/img/pc-trm-drcg-icon@1x.png" alt="">
				<b class="import_content_b">导入成功</b> 
				<span v-if="isAnalysis === 1" class="import_content_span">您已成功导入{{ successesNumber }}条数据</span>
			</div>
			<div v-if="imgFallError.status === 'SAVEFAIL' || imgFallError.status === 'CHECKFAIL' || nonAnalyticimgExhibition === false" class="import_content">
				<img class="import_content_img" src="@assets/img/pc-trm-drsb-icon@1x.png" alt="">
				<b class="import_content_b">导入失败</b> 
			</div>
		</el-dialog>
	</div>
</template>
<script>
import { $loadFileSimply } from '@const/loadFileOps'
import { fileDownload } from '@const/utils'
import { 
	uploadExcelFile, 
	getBusinessConfig, 
	getBusinessFileInfoByFileCode, 
	updateFileStatusByFileCode, 
	uploadFiles,
	download
} from '@const/fileLibraryApi'
export default {
	props: {
		uploadFileName: {					//文件名称
			type: String
		},
		configCode: {        
			type: String
		},
		params: {
			type: Object,
			default: () => {}
		}
	},
	data() {
		return {
			isCheck: 1,                            //是否校验
			isAnalysis: 1,                         //是否解析
			isSingle: 0,
			// merchantId: this.$store.state.MID,     //获取子系统的merchantId
			interval: null,                        //组件的定时任务
			returnValueList: [],
			loading: false,                        
			configureList: {                       //获取的配置信息
				describeOne: '',										 //获取下载模板的文案
				describeTwo: '',                     //获取上传文件的文案
				fileMaxRowcount: 0,                  
				fileMaxSize: 0,                      //获取上传文件的大小
				fileType: '',                        //获取文件类型
			},
			dataUpload: {
        fileDataList: [],
        fileName: [],
        uploadAccept: ''
      },
			dialogVisible: false,                  //控制组件弹框的开关
			importComplete: false,                 //打开导入成功、失败页面
			active: 1,                             //步骤
			progressVal: 0,                        //进度条
			exceptionList: '',                     //异常提示文案
			successesNumber: '',                   //成功条数
			failNumber: '',                        //失败条数
			exceptionName: '',
			errorFileCode: '',
			errorStatus: '',
			imgFallError: {},
			nonAnalyticimgExhibition: '',
			fileCode: '',
			payload: []
		}
	},
	//监听dialogVisible状态来控制进入弹框就先执行
	watch: {
		dialogVisible: {
			handler(val, oldVal) {
				if(val === true) {
					this.configurationItem()
				}
				// if(val === false) {
				// 	clearInterval(this.interval)
				// }
			},
			deep: true,
		},
		//监听进度条的进度
		progressVal: {
      handler(val, oldVal) {
        if (val === 100) {
          this.closeProgressDialog();
          this.importComplete = true;
        }
      }
    }
	},
	//生命周期清除定时任务
	beforeDestroy() {
		clearInterval(this.interval)
	},
	methods: {
		//根据业务系统id获取其在文件中心的配置项
		configurationItem() { 
			const params = {
				configCode: this.params.configCode,
				merchantId: this.params.merchantId
			}
			this.$axios.$post(getBusinessConfig, params)
			.then(res => {
				const payload = res.payload
				this.configureList.describeOne = payload.describeOne
				this.configureList.describeTwo = payload.describeTwo
				this.configureList.fileMaxRowcount = payload.fileMaxRowcount
				this.configureList.fileMaxSize = payload.fileMaxSize
				this.dataUpload.uploadAccept = payload.fileType
				this.isCheck = payload.isCheck
				this.isAnalysis = payload.isAnalysis
				this.isSingle = payload.isSingle
			})
		},
		//限制文件大小、类型，后端也限制了，前端也做一下限制
		onBeforeUpload(file, fileList) {
      let FileExt = file.name.replace(/.+\./, ''); // 名字后缀
      const isLtMB = file.size / 1024 / 1024 < this.configureList.fileMaxSize; // 文件大小
      const format = this.dataUpload.uploadAccept.includes(FileExt.toLowerCase());
      if (!format) {
        this.$message.error(`上传文件只支持${this.dataUpload.uploadAccept}类型!`);
      } else if (!isLtMB) {
        this.$message.error(`上传文件大小不能超过 ${this.configureList.fileMaxSize}MB!`);
      }
      return isLtMB && format;
    },
		//获取上传用的file
		uploadChange(file, fileList) {
      this.dataUpload.fileDataList = fileList.map(item => {
				return item.raw || item
			});
    },
		beforeRemove(file, fileList) {
			fileList.slice(file, 1)
			this.dataUpload.fileDataList = fileList;
		},
		//下载模板
		templateDownload() {
			const params = {
				url: `/guoke-deepexi-file-library/api/v1/temp/FcFileTempMgr/downloadTempByCode?tempCode=${this.params.tempCode}`,
				method: 'get',
			}
			$loadFileSimply(params)
				.then(res => {
						fileDownload(res, `${this.params.tempName}`)
				})
		},
		//解析类的校验的第一步的下一步
		nextStepOpen() {
			this.loading = true
			clearInterval(this.interval)
			let fd = new FormData();
			fd.append('file',this.dataUpload.fileDataList[0]);
			fd.append('businessInfo', JSON.stringify(this.params.businessInfo));
			fd.append('configCode', this.params.configCode)
			fd.append('merchantId', this.params.merchantId)
			this.$axios({
        method: 'post',
        url: uploadExcelFile, 
        headers: { 'Content-Type': 'multipart/form-data;' },
        data: fd
      })
			.then(res => {
				this.fileCode = res.data.payload
				this.interval = setInterval(this.getVerificationResults,500)
			})
			.finally(() => {
				this.loading = false
			})
		},
		// 解析类的校验的第二步的下一步
		secondNextStepOpen() {
			if(this.active++ > 2) {
				this.active === 3
			}
			const params = { fileCode: this.fileCode }
			this.$axios({
        method: 'post',
        url: updateFileStatusByFileCode,
        onUploadProgress: this.onUploadProgress,
        data: params
      })
			.then(res => {
				this.interval = setInterval(this.getVerification,500)
			})
		},
		// 解析类的不校验的下一步
		onCheckNextStepOpen() {
			this.loading = true
			clearInterval(this.interval)
			let fd = new FormData();
			fd.append('file',this.dataUpload.fileDataList[0]);
			fd.append('businessInfo', JSON.stringify(this.params.businessInfo));
			fd.append('operationType', this.params.operationType)
			fd.append('configCode', this.params.configCode)
			fd.append('merchantId', this.params.merchantId)
			fd.append('isCheck', 1)
			this.$axios({
        method: 'post',
        url: uploadExcelFile,
        headers: { 'Content-Type': 'multipart/form-data;' },
        data: fd
      })
			.then(res => {
				this.fileCode = res.data.payload
				this.secondNextStepOpen()
			})
		},
		// 非解析类的下一步
		nonAnalyticNextStepOpen() {
			let uploadFile = this.dataUpload.fileDataList.map(item => {
				this.loading = true
				let fd = new FormData();
				fd.append('files',item);
				fd.append('businessInfo', JSON.stringify(this.params.businessInfo));
				fd.append('configCode', this.params.configCode)
				fd.append('merchantId', this.params.merchantId)
				return this.$axios({
					method: 'post',
					url: uploadFiles, 
					onUploadProgress: this.onUploadProgress,
					headers: { 'Content-Type': 'multipart/form-data;' },
					data: fd
				})
			})
			Promise.all(uploadFile)
				.then(res => {
					let flag = res.every(item => {
						return item.data.code === '0'
					})
					this.nonAnalyticimgExhibition = flag
					this.progressVal = 100;
					this.payload = res.map(item => {
						return item.data.payload[0]
					})
					this.$emit('success', this.payload)
				})
				.finally(() => {
					this.loading = false
				})
		},
		//设置进度条进度
		getVerification() {
			this.loading = true
			const params = {
				fileCode: this.fileCode
			}
			this.$axios.$post(getBusinessFileInfoByFileCode, params)
			.then(res => {
				this.imgFallError = res.payload || {}
				if(this.imgFallError.status === 'SAVESUCCESSFUL' || this.imgFallError.status === 'SAVEFAIL') {
					clearInterval(this.interval)
					this.progressVal = 100;
					this.$emit('success')
				}
			})
		},
		//获取校验结果
		getVerificationResults() {
			this.loading = true
			const params = {
				fileCode: this.fileCode
			}
			this.$axios.$post(getBusinessFileInfoByFileCode, params)
			.then(res => {
				let resuer = res.payload
				this.exceptionList = resuer.errorMsg
				this.successesNumber =resuer.successLines
				this.failNumber = resuer.failedLines
				this.exceptionName = resuer.fileOldName.substring(0,resuer.fileOldName.indexOf('.'))
				this.errorFileCode = resuer.fileCode
				this.errorStatus = resuer.status
				this.imgFallError = resuer
				if(this.imgFallError.status === 'CHECKSUCCESSFUL' || this.imgFallError.status === 'CHECKFAIL') {
					clearInterval(this.interval)
					this.loading = false
					if(this.active === 1) {
						this.active = 2
					}
				} 
			})
			.finally(() => {
				// this.loading = false
				// if(this.active === 1) {
				// 	this.active = 2
				// }
			})
		},
		//下载异常提示
		getDownloadException() {
			const params = {
				url: `/guoke-deepexi-file-library/api/v1/business/file/downloadErrorMsgFile?fileCode=${this.errorFileCode}`,
				method: 'get'
			}
			$loadFileSimply(params)
				.then(res => {
						fileDownload(res, `${this.exceptionName}错误提示文件.txt`)
				})
		},
		// 上传进度回调
    onUploadProgress(progressEvent) {
      if (progressEvent.lengthComputable) {
        let val = (progressEvent.loaded / progressEvent.total) * 100;
        // val = parseInt(val, 10);
        if (val === 100) val = 90;
        this.progressVal = val;
      }
    },
		lastStep() {
			if(this.active-- < 2) {
				this.active = 1
			}
			clearInterval(this.interval)
			this.dataUpload.fileDataList = []
			this.configurationItem()
		},
		closePage() {
			this.$emit('turnPageUpdate')
		},
		closeProgressDialog() {
			this.loading = false
      this.dialogVisible = false;
      this.progressVal = 0;
    },
		closeTheBox() {
			this.loading = false
			clearInterval(this.interval)
			this.dialogVisible = false
			this.active = 1
			this.dataUpload.fileDataList = []
		}
	}
}
</script>
<style src="./index.less" lang="less" scoped></style>
